import Vue from 'vue'
import VueRouter from 'vue-router'
import index from '../layout/index.vue'
import Dach from '../views/Dashboard/index.vue'
import local from '../utils/local.js'
import syncrouter from './syncrouter.js'

Vue.use(VueRouter)

// 解决重复点击面包屑导航报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'index',
    component: index,
    redirect: '/Dach',
    children: [
      // 后台首页
      {
        path: '/Dach',
        meta: { name: '后台首页' },
        component: Dach
      }
    ]
  },
  {
    path: '/login',
    component: () =>
      import(/* webpackChunkName: "login" */ '../views/login.vue')
  },
  {
    path: '*',
    redirect: '/404'
  },
  {
    path: '/404',
    component: () => import(/* webpackChunkName: "err" */ '../views/err.vue')
  }
]

const router = new VueRouter({
  routes
})

// 根据一个函数在登录之后,还有页面刷新的时候计算路由
calcRoutes()
export function calcRoutes() {
  const role = local.get('role')
  const funallyRoute = filterRoute(syncrouter.routes, role)
  console.log(funallyRoute)
  // 权限设计核心方法  addRoutes 添加数组 addRoute添加对象
  routes[0].children = routes[0].children.concat(funallyRoute)
  router.addRoute(routes[0])
}

function filterRoute(arr, role) {
  // 根据定义的字段 过滤出一套数组  -true就是保留 -false就是不保留
  return arr.filter(item => {
    if (item.meta && item.meta.role) {
      // 还需要鉴权
      if (item.meta.role.includes(role)) {
        if (item.children) {
          item.children = filterRoute(item.children, role)
        }
        return true
      } else {
        return false
      }
    } else {
      // 如果没有role 数组,就可以证明可以访问的
      return true
    }
  })
}

// // 计算菜单 --
// const menus=filterMenus(routes[0].children)
// console.log(menus);

// 路由钩子  导航守卫
router.beforeEach((to, from, next) => {
  const token = local.get('token')
  if (token) {
    next()
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
